package com.yeyouluo.zk;

import org.I0Itec.zkclient.IZkChildListener;
import org.I0Itec.zkclient.ZkClient;

import java.util.Comparator;
import java.util.List;

public class ConfigRegistryServer {
    //    public final static String ZK_ADDR = "linux121:2181,linux122:2181,linux123:2181";
    public final static String ZK_ADDR = "localhost:2181";
    public static final String MYSQL_URL_PATH = "/mysql_url";
    private static final ZkClient zkClient = new ZkClient(ZK_ADDR);
    private static volatile String dbUrl;

    public ConfigRegistryServer() {

    }


    public String init() {
        if (!zkClient.exists(MYSQL_URL_PATH)) {
            zkClient.createPersistent(MYSQL_URL_PATH);
        }
        zkClient.subscribeChildChanges(MYSQL_URL_PATH, new IZkChildListener() {
            @Override
            public void handleChildChange(String s, List<String> list) throws Exception {
                // 监听子节点变化（临时顺序节点）
                System.out.println("================");
                System.out.println("发生了变化");
                System.out.println(list);
                String path = list.stream().sorted(Comparator.reverseOrder()).findFirst().get();
                System.out.println("选中的路径为：" + path);
                dbUrl = zkClient.readData(MYSQL_URL_PATH+"/"+path);
                System.out.println(">>> 数据库连接切换到" + dbUrl);
                System.out.println("================");
            }
        });
//        zkClient.createEphemeralSequential(MYSQL_URL_PATH , "127.0.0.1:3306");
        return dbUrl;
    }

    public void registDBUrl(String url) {
        String path = zkClient.createEphemeralSequential(MYSQL_URL_PATH+"/path", url);
//        System.out.println(url);
//        path  = zkClient.createEphemeralSequential(ZK_ADDR + MYSQL_URL_PATH, "222");
//        System.out.println(path);
//        System.out.println("---->>> 服务器注册成功，ip=" + ip + ";port =" + port + ";节点路径信息=" + path);
    }

    public void subscribeConfigRegistry() {

    }

}
